package com.servlet.demo.core;

import com.servlet.demo.dto.User;
import com.servlet.demo.enums.UserType;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

public class UserCoreService {
    private static List<User> userList = Collections.synchronizedList(new ArrayList<User>());
    // 静态初始化用户列表，用于demo省略数据库操作
    static {
        // 管理员
        userList.add(new User(UserType.ADMIN, 99L, "admin", "admin"));
        // 普通用户
        userList.add(new User(UserType.USER, 1L, "zhangsan", "123456"));
        userList.add(new User(UserType.USER, 2L, "lisi", "123456"));
        userList.add(new User(UserType.USER, 3L, "wangwu", "123456"));
        userList.add(new User(UserType.USER, 4L, "zhaoqi", "123456"));
        userList.add(new User(UserType.USER, 5L, "wangsanhua", "123456"));
        userList.add(new User(UserType.USER, 6L, "xiaocainiao", "123456"));
        userList.add(new User(UserType.USER, 7L, "jiashiyuan", "123456"));
    }

    /**
     * 获取全部用户列表
     * @return
     */
    public List<User> getUserList() {
        return userList;
    }

    /**
     * 根据用户ID筛选用户信息（因为正常情况下用户ID唯一）
     * @param userId    用户ID
     * @return
     */
    public User getUserById(Long userId) {
        List<User> list = userList.stream().filter(u -> u.getUserId()==userId).collect(Collectors.toList());
        if (list == null) {
            return null;
        }
        return list.get(0);
    }

    /**
     * 添加普通用户
     * @param account
     * @param password
     */
    public void addUser(String account, String password){
        // 创建线程安全锁
        Lock lock = new ReentrantLock();
        // 锁
        lock.lock();
        // 执行
        try {
            userList.add(new User(UserType.USER, getLastUserId(), account, password));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 不管是否出错，都解锁
            lock.unlock();
        }
    }

    /**
     * 根据用户ID，删除用户
     * @param userId
     * @return
     */
    public int removeUser(Long userId) {
        int count = 0;
        try {
            userList.removeIf(u->userId.equals(u.getUserId()));
            count++;
        } catch (Exception e) {
            count--;
            e.printStackTrace();
        }
        return count;
    }

    /**
     * 根据账号密码获取用户信息
     * @param account   账号
     * @param password  密码
     * @return
     */
    public User getUserByLogin(String account, String password) {
        for (int i = 0; i < userList.size(); i++) {
            User user = userList.get(i);
            if (user.getAccount().equals(account) && user.getPassword().equals(password)) {
                return user;
            }
        }
        return null;
    }

    /**
     * 获取最后一次插入用户ID
     * @return
     */
    private Long getLastUserId() {
        Collections.sort(userList, Comparator.comparing(User::getUserId).reversed());
        return userList.get(0).getUserId();
    }

}
